<template>
  <page-container>
    <a-card>
      <div class="form">
        <a-form
          :model="formState"
          :label-col="labelCol"
          ref="formRef"
          :rules="rules"
          :wrapper-col="wrapperCol"
        >
          <a-form-item label="流转单ID">{{ formState.id }}</a-form-item>
          <a-form-item label="流转单标题" name="title">
            <a-input
              v-model:value="formState.title"
              type="textarea"
              placeholder="输入流转单标题内容"
            />
          </a-form-item>
          <a-form-item label="推送人" name="basicPerson">
            <a-input
              v-model:value="formState.basicPerson"
              type="textarea"
              placeholder="输入推送人"
            />
          </a-form-item>
          <a-form-item label="推送类别" name="newType" style="position: relative">
            <a-select
              v-model:value="formState.newType"
              placeholder="选择推送类别"
              style="width: 45%"
              @change="handleType"
            >
              <a-select-option :value="item.code" v-for="item in typeList" :key="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item name="oldType" style="position: relative; right: -49%; margin-top: -63px">
            <a-select
              v-model:value="formState.oldType"
              placeholder="选择推送类别"
              style="width: 45%"
            >
              <a-select-option :value="item.code" v-for="item in oldTypeList" :key="item.code">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <a-button class="setupclass" @click="handleSet">
              <img src="@/assets/sz.png" alt="" />
              设置
            </a-button>
          </a-form-item>
          <a-form-item label="审批领导" name="approveUserId">
            <a-select
              @change="approvePersonChange"
              v-model:value="formState.approveUserId"
              placeholder="请选择审批领导"
            >
              <a-select-option
                v-for="item in approvePersonList"
                :value="item.userId"
                :key="item.userId"
              >
                {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="接收人员" name="handlePersonId">
            <a-select
              v-model:value="formState.handlePersonId"
              @change="unitChange"
              placeholder="请选择接收人员"
            >
              <a-select-option
                :value="item.handlePersonId"
                v-for="(item, index) in unitList"
                :key="index"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <!-- <a-form-item label="辖区民警" name="handlePersonId">
            <a-input
              v-model:value="formState.handlePerson"
              type="textarea"
              placeholder="请输入辖区民警"
              disabled
            />
          </a-form-item> -->
          <a-form-item label="处理期限" name="handleStartTime">
            <!-- <a-select v-model:value="formState.handleDay" placeholder="请选择处理期限">
              <a-select-option :value="item.value" v-for="item in dayList" :key="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select> -->
            <!-- <a-radio-group v-model:value="handleDayValue" @change="handleChange" name="radioGroup">
              <a-radio value="5">5天</a-radio>
              <a-radio value="7">7天</a-radio>
              <a-radio value="0">其他</a-radio>
              <div style="float: right; width: 100px; display: flex; align-items: center">
                <a-input-number
                  min="1"
                  v-model:value="daysNumber"
                  @focus="handleFocus"
                  @blur="handleBlur"
                  style="float: left"
                />
                <span style="margin-left: 10px">天</span>
              </div>
            </a-radio-group> -->
            <!-- <a-range-picker
              style="width: 100%"
              show-time
              :disabled-date="disabledDate"
              v-model:value="timeArr"
              @change="handlecaseBegintime"
            /> -->
            <pickers
              style="width: 100%"
              v-model:value="timeArr"
              :data="timeArr"
              @setTime="handlecaseBegintime"
              :disabled="disabledDate"
            />
          </a-form-item>
          <a-form-item label="推送情况" name="basicContent">
            <a-textarea
              v-model:value="formState.basicContent"
              placeholder="请输入推送情况"
              style="min-height: 200px"
            />
          </a-form-item>
          <a-form-item label="下发附件">
            <a-upload
              :file-list="fileList"
              :multiple="true"
              name="file"
              @change="handleChange"
              :before-upload="beforeUpload"
            >
              <a-button type="dashed">
                <upload-outlined></upload-outlined>
                上传附件
              </a-button>
            </a-upload>
          </a-form-item>
        </a-form>
      </div>
      <div class="bottomc">
        <div class="buttonContent">
          <a-button @click="handleBrak">取消</a-button>
          <a-button
            :loading="loadings"
            type="primary"
            style="margin-left: 10px"
            @click="handleOk(0)"
          >
            保存
          </a-button>
          <a-button
            type="primary"
            style="margin-left: 10px"
            @click="handleOk(1)"
            :loading="loading"
          >
            提交审批
          </a-button>
        </div>
      </div>
    </a-card>
    <setModal ref="setMOdal" @handleData="handleProcessTypeTree" @handleQuery="handleSetdata" />
  </page-container>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, onActivated, onMounted, nextTick } from 'vue';
import type { UnwrapRef } from 'vue';
import {
  insert,
  queryBasicId,
  getQueryXqdwList,
  queryApproveLeader,
  ProcessTypeTree,
} from '@/api/smart-tools/index';
import { addrules } from './rules';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import moment from 'moment';
import { UploadOutlined } from '@ant-design/icons-vue';
import setModal from './components/setModal.vue';
import pickers from '@/components/s-picker/picker.vue';
interface FormState {
  id: string;
  title: string; //标题
  basicPerson: string; //推送人
  type: string | undefined; //推送类别
  newType: string | undefined; //推送类别
  oldType: string | undefined; //推送类别
  handleUnit: string | undefined; //下发辖区
  handlePersonId: string | undefined; //辖区民警
  handlePerson: string | undefined; //辖区民警
  handleStartTime: string | number | undefined; //处理期限
  handleEndTime: string | number | undefined; //处理期限
  basicContent: string; //推送情况
  status: string;
  approveUserId: string | undefined;
  approvePerson: string | undefined;
}
interface FileItem {
  uid: string;
  name?: string;
  status?: string;
  response?: string;
  url?: string;
  preview?: string;
  originFileObj?: any;
  file: Blob;
}
export default defineComponent({
  components: { UploadOutlined, setModal, pickers },
  setup() {
    const fileList = ref<any>([]);
    let timeArr = ref([]);
    const rules = addrules();
    let oldTypeList = ref<any>([]);
    //下发辖区
    const unitList = ref<any>([]);
    //辖区民警
    const personList = ref<any>([]);
    //处理期限
    const dayList = [
      {
        name: '一天',
        value: '1',
      },
      {
        name: '5天',
        value: '2',
      },
    ];

    const router = useRouter();
    const formState: UnwrapRef<FormState> = reactive({
      id: '',
      title: router.currentRoute.value.query.title
        ? (router.currentRoute.value.query.title as string)
        : '五里冲派出所综合指挥室流转单',
      basicPerson: '综合指挥室指挥调度组',
      type: undefined,
      handleUnit: undefined,
      handlePersonId: undefined,
      handlePerson: undefined,
      handleStartTime: '',
      handleEndTime: '',
      approveUserId: undefined,
      approvePerson: undefined,
      basicContent: router.currentRoute.value.query.basicContent
        ? (router.currentRoute.value.query.basicContent as string)
        : '',
      status: '0',
      oldType: router.currentRoute.value.query.oldType
        ? (router.currentRoute.value.query.oldType as string)
        : '11',
      newType: router.currentRoute.value.query.newType
        ? (router.currentRoute.value.query.newType as string)
        : '1',
    });
    const handleDayValue = ref<string>('5');
    const loading = ref<boolean>(false);
    const loadings = ref<boolean>(false);
    const formRef = ref();
    const handleOk = value => {
      if (value == 0) {
        loadings.value = true;
        formState.status = '-1';
      } else {
        loading.value = true;
        formState.status = '0';
      }
      formRef.value
        .validate()
        .then(() => {
          formState.type = (formState.newType as string) + ',' + formState.oldType;
          const formData = new FormData();
          fileList.value.forEach((file: FileItem) => {
            formData.append('file', file.originFileObj);
          });
          //0保存 1提交审批
          formData.append('operation', value);
          Object.keys(formState).forEach(key => {
            formData.append(key, formState[key]);
          });
          insert(formData).then(res => {
            if (res.code === 200) {
              message.success('成功!');
              loading.value = false;
              loadings.value = false;
              handlecancel();
            }
          });
        })
        .catch(error => {
          loading.value = false;
          loadings.value = false;
          console.log('error', error);
        });
    };
    const handlequeryBasicId = () => {
      queryBasicId().then(res => {
        formState.id = res.data;
      });
    };
    const handleBrak = () => {
      handlecancel();
    };
    const handlecancel = () => {
      if (!isDetail.value) {
        router.back();
      } else {
        router.push({
          path: '/single-initiator/list',
        });
      }
    };
    const approvePersonChange = value => {
      approvePersonList.value.filter(item => {
        if (item.userId == value) {
          formState.approvePerson = item.userName;
        }
      });
    };
    const queryXqdwList = () => {
      getQueryXqdwList().then(res => {
        if (res.code === 200) {
          unitList.value = [];
          res.data.forEach(item => {
            if (item.userId) {
              unitList.value.push({
                name: item.xqdwNameJc + (item.userName ? ` (${item.userName})` : ''),
                value: item.xqdwCode,
                handlePersonId: item.userId,
                handlePerson: item.userName,
              });
            }
          });
        }
      });
    };
    //通过辖区查询民警
    const unitChange = value => {
      unitList.value.forEach(item => {
        if (item.handlePersonId == value) {
          formState.handleUnit = item.value;
          formState.handlePerson = item.handlePerson;
        }
      });
    };
    //辖区民警
    const personChange = (value, option) => {
      formState.handlePersonId = value;
      formState.handlePerson = option.children[0].children;
    };
    const handlecaseBegintime = value => {
      formState.handleStartTime = value[0];
      formState.handleEndTime = value[1];
    };
    const handleChange = info => {
      let resFileList = [...info.fileList];
      resFileList = resFileList.map(file => {
        if (file.response) {
          file.url = file.response.url;
        }
        return file;
      });
      fileList.value = resFileList;
    };
    const beforeUpload = (file: FileItem) => {
      fileList.value = [...fileList.value, file];
      return false;
    };
    const isDetail = ref<boolean>(false);
    const approvePersonList = ref<any>([]);
    const handlequeryApproveLeader = () => {
      queryApproveLeader().then(res => {
        approvePersonList.value = res.data;
      });
    };
    //警用部分日期
    const disabledDate = current => {
      return current && current < moment().startOf('day');
    };
    //设置
    const setMOdal = ref();
    const handleSet = () => {
      setMOdal.value.showModal();
      setMOdal.value.handleProcessTypeTree();
    };
    //推送类别数据
    const typeList = ref<any>([]);
    const handleProcessTypeTree = () => {
      ProcessTypeTree().then(res => {
        typeList.value = res.data;
        typeList.value.find(item => {
          if (item.code == 1) {
            oldTypeList.value = item.children;
          }
        });
      });
    };
    const handleType = value => {
      oldTypeList.value = [];
      formState.oldType = undefined;
      typeList.value.find(item => {
        if (item.code == value) {
          oldTypeList.value = item.children;
        }
      });
    };
    const handleSetdata = () => {
      ProcessTypeTree().then(res => {
        typeList.value = res.data;
        typeList.value.find(item => {
          if (item.code == formState.newType) {
            oldTypeList.value = item.children;
          }
        });
        let newTpyeIndex = typeList.value.findIndex(item => item.code == formState.newType);
        if ((newTpyeIndex as number) < 0) {
          formState.newType = undefined;
          oldTypeList.value = [];
        }
        let oldTypeIndexFlag = ref<boolean>(false);
        typeList.value.forEach(item => {
          if (item.children?.length) {
            item.children.forEach(el => {
              if (el.code == formState.oldType) {
                oldTypeIndexFlag.value = true;
              }
            });
          }
        });

        if (!oldTypeIndexFlag.value) {
          formState.oldType = undefined;
        }
      });
    };
    onMounted(() => {
      if (router.currentRoute.value.query.title) {
        isDetail.value = true;
      }
      if (router.currentRoute.value.query.detaillist) {
        let detailQuery = JSON.parse(router.currentRoute.value.query.detaillist as string);
        if (detailQuery) {
          //   console.log('执行了', detailQuery.securityNo);
        }
      }
    });
    onActivated(() => {
      handleProcessTypeTree();
      queryXqdwList();
      handlequeryBasicId();
      handlequeryApproveLeader();
      formRef.value.resetFields();
      timeArr.value = [];
      fileList.value = [];
    });

    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      setMOdal,
      handleSet,
      handleSetdata,
      fileList,
      timeArr,
      beforeUpload,
      formState,
      approvePersonList,
      router,
      typeList,
      unitList,
      personList,
      handleBrak,
      dayList,
      rules,
      handleOk,
      formRef,
      loading,
      loadings,
      handleDayValue,
      handleChange,
      unitChange,
      personChange,
      oldTypeList,
      handleType,
      handlecaseBegintime,
      isDetail,
      disabledDate,
      approvePersonChange,
      handleProcessTypeTree,
    };
  },
});
</script>
<style lang="less" scoped>
.form {
  width: 50%;
  margin: 0 auto;
  padding: 30px;
  .lbType {
    display: flex;
    justify-content: space-between;
  }
}
.bottomc {
  display: flex;
  align-items: center;
  width: 100%;
  height: 70px;
  border-top: 1px solid #3f424d;
  .buttonContent {
    width: 300px;
    margin: 0 auto;
  }
}
.setupclass {
  position: relative;
  top: 0px;
  right: -14px;
  background: #3b3d44;
  img {
    margin-bottom: 3px;
  }
}
:deep(.ant-card-body) {
  padding: 0;
}
:deep(.ant-btn-dashed) {
  color: #205ee9;
  border-color: #205ee9;
}
</style>
